class Dog:
    """一个表示狗的简单类"""

    def __init__(self, name):
        """初始化方法"""
        self.name = name  # 定义实例属性

    def bark(self):
        """实例方法"""
        print(f"{self.name} 在叫：汪汪！")


# 创建对象实例
my_dog = Dog("旺财")
my_dog.bark()  # 输出：旺财 在叫：汪汪！


class Rectangle:
    """矩形类"""

    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.area = width * height  # 可以在初始化时计算属性

    def calculate_perimeter(self):
        """计算周长"""
        return 2 * (self.width + self.height)

    def resize(self, new_width, new_height):
        """调整矩形大小"""
        self.width = new_width
        self.height = new_height
        self.area = new_width * new_height  # 更新面积


# 使用示例
rect = Rectangle(5, 3)
print(f"面积: {rect.area}")  # 面积: 15
print(f"周长: {rect.calculate_perimeter()}")  # 周长: 16
rect.resize(7, 4)
print(f"新面积: {rect.area}")  # 新面积: 28


class Student:
    """学生类"""

    def __init__(self, name, age=18, major="未定"):
        self.name = name
        self.age = age
        self.major = major
        self.courses = []  # 初始化为空列表

    def enroll(self, course):
        """选课方法"""
        self.courses.append(course)
        print(f"{self.name} 已选课: {course}")


# 使用示例
student1 = Student("张三")
student2 = Student("李四", 20, "计算机科学")

print(student1.major)  # 输出：未定
student1.enroll("Python编程")  # 输出：张三 已选课: Python编程


class BankAccount:
    """银行账户类"""

    def __init__(self, account_holder, initial_balance=0):
        if initial_balance < 0:
            raise ValueError("初始余额不能为负")

        self.account_holder = account_holder
        self.balance = initial_balance
        self.transactions = []

    def deposit(self, amount):
        """存款"""
        if amount <= 0:
            print("存款金额必须大于0")
            return

        self.balance += amount
        self.transactions.append(f"存款: +{amount}")

    def withdraw(self, amount):
        """取款"""
        if amount <= 0:
            print("取款金额必须大于0")
            return
        if amount > self.balance:
            print("余额不足")
            return

        self.balance -= amount
        self.transactions.append(f"取款: -{amount}")


# 使用示例
try:
    account = BankAccount("王五", 1000)
    account.deposit(500)
    account.withdraw(200)
    print(f"当前余额: {account.balance}")  # 输出：1300
    print("交易记录:", account.transactions)
except ValueError as e:
    print(e)


class Car:
    # 类属性（所有实例共享）
    wheels = 4

    def __init__(self, brand, model):
        # 实例属性（每个实例独有）
        self.brand = brand
        self.model = model

    @classmethod
    def change_wheels(cls, new_count):
        """修改类属性"""
        cls.wheels = new_count


# 使用示例
car1 = Car("Toyota", "Camry")
car2 = Car("Honda", "Accord")

print(car1.wheels)  # 4 (通过实例访问类属性)
print(Car.wheels)  # 4 (通过类访问类属性)

Car.change_wheels(6)  # 修改类属性
print(car2.wheels)  # 6 (所有实例都会看到变化)


class SecretKeeper:
    """演示私有属性"""

    def __init__(self, public_info, secret_info):
        self.public = public_info
        self.__secret = secret_info  # 双下划线开头的属性

    def reveal_secret(self):
        """访问私有属性的方法"""
        return self.__secret


# 使用示例
keeper = SecretKeeper("公开信息", "机密信息")

print(keeper.public)  # 输出：公开信息
# print(keeper.__secret)    # 报错：AttributeError
print(keeper.reveal_secret())  # 输出：机密信息
print(keeper._SecretKeeper__secret)  # 实际存储名称（但不建议这样访问）


class GameCharacter:
    """游戏角色类"""

    MAX_HEALTH = 100  # 类常量

    def __init__(self, name, attack_power=10):
        self.name = name
        self.health = self.MAX_HEALTH
        self.attack_power = attack_power
        self.is_alive = True

    def attack(self, other):
        """攻击另一个角色"""
        if not self.is_alive:
            print(f"{self.name} 已经死亡，无法攻击")
            return

        print(f"{self.name} 攻击了 {other.name}！")
        other.take_damage(self.attack_power)

    def take_damage(self, amount):
        """受到伤害"""
        if not self.is_alive:
            return

        self.health -= amount
        print(f"{self.name} 受到 {amount} 点伤害")

        if self.health <= 0:
            self.die()

    def die(self):
        """角色死亡"""
        self.is_alive = False
        self.health = 0
        print(f"{self.name} 已经死亡！")

def heal(self, amount):
        """治疗角色"""
        if not self.is_alive:
            print(f"{self.name} 已经死亡，无法治疗")
            return

        self.health = min(self.MAX_HEALTH, self.health + amount)
        print(f"{self.name} 恢复了 {amount} 点生命值，当前生命值: {self.health}")

def __str__(self):
        """定义对象的字符串表示"""
        status = "存活" if self.is_alive else "死亡"
        return f"{self.name} [生命值: {self.health}/{self.MAX_HEALTH}, 状态: {status}]"


# 使用示例
hero = GameCharacter("英雄", attack_power=15)
monster = GameCharacter("怪物")

print(hero)  # 输出：英雄 [生命值: 100/100, 状态: 存活]

hero.attack(monster)  # 英雄 攻击了 怪物！
# 怪物 受到 15 点伤害
print(monster)  # 怪物 [生命值: 85/100, 状态: 存活]

monster.attack(hero)  # 怪物 攻击了 英雄！
# 英雄 受到 10 点伤害
print(hero)  # 英雄 [生命值: 90/100, 状态: 存活]

hero.heal(20)  # 英雄 恢复了 20 点生命值，当前生命值: 100


class Student:
    """学生类，包含姓名、年龄和成绩"""

    def __init__(self, name, age, score):
        """初始化学生属性"""
        self.name = name  # 姓名属性
        self.age = age  # 年龄属性
        self.score = score  # 成绩属性

    def display_info(self):
        """显示学生信息"""
        print(f"姓名: {self.name}, 年龄: {self.age}, 成绩: {self.score}")

    def is_passing(self, passing_grade=60):
        """检查学生是否及格"""
        return self.score >= passing_grade


# 创建学生对象
student1 = Student("张三", 18, 85)
student2 = Student("李四", 19, 55)
student3 = Student("王五", 20, 92)

# 调用方法
student1.display_info()  # 输出: 姓名: 张三, 年龄: 18, 成绩: 85
print(f"{student2.name}是否及格: {student2.is_passing()}")  # 输出: 李四是否及格: False






# 学生数据列表
student_data = [
    {"name": "张三", "age": 18, "score": 85},
    {"name": "李四", "age": 19, "score": 55},
    {"name": "王五", "age": 20, "score": 92},
    {"name": "赵六", "age": 18, "score": 78},
    {"name": "钱七", "age": 19, "score": 63}
]

# 批量创建学生对象
students = [Student(data["name"], data["age"], data["score"]) for data in student_data]

# 显示所有学生信息
for i, student in enumerate(students, 1):
    print(f"学生{i}:")
    student.display_info()
    print()


class Student:
    """增强版学生类"""

    def __init__(self, name, age, score):


        # 输入验证
        if not isinstance(name, str) or len(name.strip()) == 0:
            raise ValueError("姓名必须是非空字符串")
        if not isinstance(age, int) or age <= 0:
            raise ValueError("年龄必须是正整数")
        if not isinstance(score, (int, float)) or score < 0 or score > 100:
            raise ValueError("成绩必须是0-100之间的数字")

        self.name = name.strip()
        self.age = age
        self.score = score
        self.grade = self._calculate_grade()

    def _calculate_grade(self):
        """计算等级(A/B/C/D/F)"""
        if self.score >= 90:
            return 'A'
        elif self.score >= 80:
            return 'B'
        elif self.score >= 70:
            return 'C'
        elif self.score >= 60:
            return 'D'
        else:
            return 'F'

    def display_info(self):
        """显示完整学生信息"""
        print(f"姓名: {self.name}")
        print(f"年龄: {self.age}岁")
        print(f"成绩: {self.score}分")
        print(f"等级: {self.grade}")
        print(f"状态: {'及格' if self.is_passing() else '不及格'}")

    def is_passing(self, passing_grade=60):
        """检查是否及格"""
        return self.score >= passing_grade

    def __str__(self):
        """定义对象的字符串表示"""
        return f"Student({self.name}, {self.age}, {self.score})"

    def __repr__(self):
        """定义对象的官方字符串表示"""
        return f"<Student name={self.name} age={self.age} score={self.score}>"


# 使用示例
try:
    student = Student(" 李明 ", 19, 88.5)
    student.display_info()
    """
    输出:
    姓名: 李明
    年龄: 19岁
    成绩: 88.5分
    等级: B
    状态: 及格
    """

    print(student)  # 调用__str__: Student(李明, 19, 88.5)
    print(repr(student))  # 调用__repr__: <Student name=李明 age=19 score=88.5>

    # 测试错误输入
    # bad_student = Student("", -20, 150)  # 会抛出ValueError
except ValueError as e:
    print(f"错误: {e}")


class StudentManager:
    """学生管理类"""

    def __init__(self):
        self.students = []

    def add_student(self, student):
        """添加学生"""
        if isinstance(student, Student):
            self.students.append(student)
        else:
            raise TypeError("只能添加Student对象")

    def average_score(self):
        """计算平均成绩"""
        if not self.students:
            return 0
        return sum(s.score for s in self.students) / len(self.students)

    def top_students(self, n=3):
        """获取成绩最好的n个学生"""
        return sorted(self.students, key=lambda s: s.score, reverse=True)[:n]

    def passing_rate(self):
        """计算及格率"""
        if not self.students:
            return 0
        passing = sum(1 for s in self.students if s.is_passing())
        return passing / len(self.students) * 100


# 使用示例
manager = StudentManager()

# 添加学生
manager.add_student(Student("张三", 18, 85))
manager.add_student(Student("李四", 19, 55))
manager.add_student(Student("王五", 20, 92))
manager.add_student(Student("赵六", 18, 78))
manager.add_student(Student("钱七", 19, 63))

# 统计信息
print(f"平均成绩: {manager.average_score():.1f}")
print(f"及格率: {manager.passing_rate():.1f}%")
print("\n成绩最好的3名学生:")
for student in manager.top_students():
    print(f"- {student.name}: {student.score}分")